package com.applink.sell_proof.fragment;

import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.applink.sell_proof.BasePagerActivity;
import com.applink.sell_proof.R;
import com.applink.sell_proof.TipNotificationDialog;
import com.applink.sell_proof.api.DataHelper;
import com.applink.sell_proof.builder.TipBuilder;
import com.applink.sell_proof.constant.Constant;
import com.applink.sell_proof.constant.IntentKey;
import com.applink.sell_proof.database.EMarketingContentProvider;
import com.applink.sell_proof.database.table.TipDBHelper;
import com.applink.sell_proof.model.Tip;
import com.applink.sell_proof.util.Utility;

public class TipsLearn extends SherlockFragment implements
		LoaderCallbacks<Cursor>, OnScrollListener, OnClickListener,
		OnEditorActionListener {

	protected ViewGroup mLayout;
	protected TipBuilder mTipBuider;
	protected View mHeaderPrevious;
	protected View mHeaderToday;
	public static Boolean isDownload = false;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		if (mLayout == null) {
			mLayout = (ViewGroup) inflater.inflate(R.layout.tipsofday, null,
					false);
		} else {
			if (mLayout.getParent() != null) {
				((ViewGroup) mLayout.getParent()).removeView(mLayout);
			}
		}

		mHeaderPrevious = LayoutInflater.from(getActivity()).inflate(
				R.layout.header_previous_tip, null);

		mHeaderToday = LayoutInflater.from(getActivity()).inflate(
				R.layout.header_today_tip, null);

		//((ListView) mLayout.findViewById(android.R.id.list)).addHeaderView(
			//	mHeaderToday, null, false);

		((ListView) mLayout.findViewById(android.R.id.list)).addHeaderView(
				mHeaderPrevious, null, false);

		mHeaderPrevious.setVisibility(View.INVISIBLE);
		mHeaderToday.setVisibility(View.INVISIBLE);
		mHeaderToday.findViewById(R.id.tip_today).setOnClickListener(this);

		setHasOptionsMenu(true);
		((ListView) mLayout.findViewById(android.R.id.list))
				.setOnScrollListener(this);
		
		return mLayout;
	}	
	
	 
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		getActivity().getSupportLoaderManager().initLoader(0, null, this);
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		inflater.inflate(R.menu.menu_tip, menu);
		MenuItem search_bar = menu.findItem(R.id.search_bar);
		EditText searchBox = (EditText) search_bar.getActionView()
				.findViewById(R.id.et_search_bar);
		searchBox.setOnEditorActionListener(this);
		DataHelper.getInstance().getTips(1, 100, getCatogery());
	}

	@Override
	public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {

		return new CursorLoader(getActivity(),
				EMarketingContentProvider.TIP_CONTENT_URI, null,
				TipDBHelper.TIP_CATEGORY + "=?",
				new String[] { Integer.toString(getCatogery().toInt()) },
				TipDBHelper.TIP_DATE + " DESC");

	}

	@SuppressWarnings("unchecked")
	@Override
	public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
		if(Utility.checkLoadTipAgain == true){
			Utility.checkLoadTipAgain = false;
			return;
		}
		if (Utility.checkTip == true) {
			//DataHelper.getInstance().getTips(1, 100, getCatogery());
			if (data != null && loader.getId() == 0) {

				List<Tip> tips = new ArrayList<Tip>();

				int year = GregorianCalendar.getInstance().get(
						GregorianCalendar.YEAR);
				int month = GregorianCalendar.getInstance().get(
						GregorianCalendar.MONTH);
				int day = GregorianCalendar.getInstance().get(
						GregorianCalendar.DATE);
				long date = new GregorianCalendar(year, month, day)
						.getTimeInMillis();

				if (data.moveToFirst()) {
					do {
						Tip tip = new Tip();
						tip.setDate(data.getLong(data
								.getColumnIndex(TipDBHelper.TIP_DATE)));
						tip.setId(data.getLong(data
								.getColumnIndex(TipDBHelper.TIP_ID)));
						tip.setName(data.getString(data
								.getColumnIndex(TipDBHelper.TIP_NAME)));
						tip.setParagraph(data.getString(data
								.getColumnIndex(TipDBHelper.TIP_PARAGRAPH)));
						//tip.setSave(data.getString(data.getColumnIndex(TipDBHelper.TIP_SAVE)).equals("True"));
						tip.setSave(data.getInt(data
								.getColumnIndex(TipDBHelper.TIP_SAVE)) == 1);
//						if (tip.getDate() == date) {
//							// set tip of day
//							mHeaderToday.setVisibility(View.VISIBLE);
//							((TextView) mHeaderToday
//									.findViewById(R.id.tip_name)).setText(tip
//									.getName());
//							((TextView) mHeaderToday
//									.findViewById(R.id.tip_paragraph))
//									.setText(tip.getParagraph());
//							String formatDate = DateFormat.getDateFormat(
//									getActivity()).format(
//									new Date(tip.getDate()));
//							((TextView) mHeaderToday
//									.findViewById(R.id.tip_date))
//									.setText(formatDate);
//							mHeaderToday.findViewById(R.id.tip_today).setTag(
//									tip);
//							mHeaderToday.findViewById(R.id.tip_save_icon)
//							.setVisibility(View.VISIBLE);
//////							mHeaderToday.findViewById(R.id.tip_save_icon)
//////									.setVisibility(
//////											tip.isSave() ? View.VISIBLE
//////													: View.INVISIBLE);
//						} else {
//							tips.add(tip);
//						}
						tips.add(tip);
					} while (data.moveToNext());

					if (tips.size() > 0) {
						mHeaderPrevious.setVisibility(View.VISIBLE);

						if (mTipBuider != null) {
							mTipBuider.clear();
							((ArrayList<Tip>) mTipBuider.getData())
									.addAll(tips);
							mTipBuider.notifyDataChange();

							return;
						}

						mTipBuider = new TipBuilder(getActivity(), mLayout);
						mTipBuider.setData(tips);
						isDownload = true;
					} else {
						mHeaderPrevious.setVisibility(View.INVISIBLE);

						//DataHelper.getInstance().getTips(1, 100, getCatogery());

					}
				} else {

				//	DataHelper.getInstance().getTips(1, 100, getCatogery());

				}

				Log.e("all tip learn", "on load finish " + loader.getId()
						+ " data size " + tips.size());
				View loading = mLayout
						.findViewById(com.applink.sell_proof.R.id.pb_loading);
				if (loading != null)
					loading.setVisibility(View.GONE);
			}
		}

	}

	@Override
	public void onLoaderReset(Loader<Cursor> arg0) {
	}

	protected int mVisibleItem;
	protected int mFirstVisibleItem;

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		mVisibleItem = visibleItemCount;
		mFirstVisibleItem = firstVisibleItem;
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
//		if (scrollState == SCROLL_STATE_IDLE
//				&& mVisibleItem > 0
//				&& mFirstVisibleItem + mVisibleItem >= mTipBuider.getData()
//						.size()) {
//			DataHelper.getInstance().getTips(1,
//					100, getCatogery());
//		}
	}

	@Override
	public void onClick(View v) {
		
		switch (v.getId()) {
		case R.id.tip_today:
			Utility.checkLoadTipAgain = true;
			Tip tip = (Tip) v.getTag();
			Intent intent = new Intent(getActivity(),
					TipNotificationDialog.class);
			int indexActivity = ((BasePagerActivity) getActivity())
					.getActivityIndex();
			intent.putExtra(IntentKey.ACTIVITY_NAME, indexActivity);
			intent.putExtra(Constant.KEY_TIP, tip);
			getActivity().startActivity(intent);
			break;

		default:
			break;
		}

	}

	@Override
	public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
		if (actionId == EditorInfo.IME_ACTION_SEARCH) {
			SearchTip searchResult = (SearchTip) getActivity()
					.getSupportFragmentManager().findFragmentByTag(
							SearchTip.TAG);
			if (searchResult == null)
				searchResult = new SearchTip();
			FragmentTransaction transaction = getActivity()
					.getSupportFragmentManager().beginTransaction();
			transaction.replace(R.id.main_container, searchResult,
					SearchTip.TAG);
			transaction.addToBackStack(null);
			transaction.commit();
			searchResult.searchTip(v.getText().toString(), getCatogery());
			InputMethodManager imm = (InputMethodManager) getActivity()
					.getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
			return true;
		}

		return false;
	}

	protected Tip.Category getCatogery() {
		return Tip.Category.LEARN;
	}
}
